package com.kyivmohyla.kma2.client.view.manager;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.ListDataProvider;
import com.kyivmohyla.kma2.client.UserService;
import com.kyivmohyla.kma2.client.utils.Dialog;
import com.kyivmohyla.kma2.client.view.common.EquipmentCellTableWidget;
import com.kyivmohyla.kma2.client.view.common.OrderHistoryWidget;
import com.kyivmohyla.kma2.client.view.common.ServiceCellTableWidget;
import com.kyivmohyla.kma2.shared.model.*;

import java.util.ArrayList;
import java.util.List;

public class ClosedOrderView extends PopupPanel {
    private static ClosedOrderViewUiBinder ourUiBinder = GWT.create(ClosedOrderViewUiBinder.class);

    @UiField
    protected Button close;
    @UiField
    protected TextBox state;
    @UiField
    protected TextBox customerName;
    @UiField
    protected TextBox customerPhone;
    @UiField
    protected TextArea customerAddress;
    @UiField
    protected TextBox customerEmail;
    @UiField
    protected DateBox plannedDate;
    @UiField
    protected ListBox startTime;
    @UiField
    protected ListBox endTime;
    @UiField
    protected TextArea commentary;
    @UiField
    protected ListBox engineerList;
    @UiField
    protected ServiceCellTableWidget serviceCellTable;
    @UiField
    protected EquipmentCellTableWidget equipmentCellTable;
    @UiField
    protected OrderHistoryWidget orderHistoryCellTable;

    private final static String timeFormatString = "HH:mm";
    private final static String dateFormatString = "dd.MM.yyyy";
    private final static DateTimeFormat timeFormat = DateTimeFormat.getFormat(timeFormatString);
    private final static DateTimeFormat dateFormat = DateTimeFormat.getFormat(dateFormatString);
    private UIOrder existingOrder;
    private List<UIService> servicesOnOrderToShow;
    private List<UIEquipment> equipmentOnOrderToShow;

    public ClosedOrderView(UIOrder uiOrder) {
        super(false);
        add(ourUiBinder.createAndBindUi(this));

        this.close.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                ClosedOrderView.this.hide();
            }
        });

        this.existingOrder = uiOrder;
        this.state.setText(uiOrder.getStateName());
        this.plannedDate.setFormat(new DateBox.DefaultFormat(dateFormat));
        if (uiOrder.getDesStartDate() != null) {
            this.plannedDate.getTextBox().setText(dateFormat.format(uiOrder.getDesStartDate()));
        }
        if (uiOrder.getStartDate() != null) {
            this.startTime.addItem(timeFormat.format(uiOrder.getStartDate()));
        }
        if (uiOrder.getEndDate() != null) {
            this.endTime.addItem(timeFormat.format(uiOrder.getEndDate()));
        }
        this.commentary.setText(uiOrder.getCommentary());
        this.customerName.setText(uiOrder.getCustomerName());

        UserService.App.getInstance().getCustomerById(uiOrder.getCustomerId(), new AsyncCallback<UICustomer>() {
            @Override
            public void onFailure(Throwable caught) {
                Dialog.getInstance().createDialogBoxWithMessage("Error", caught.getMessage());
            }

            @Override
            public void onSuccess(UICustomer result) {
                customerPhone.setText(result.getPhone());
                customerAddress.setText(result.getAddress());
                customerEmail.setText(result.getEmail());
            }
        });

        UserService.App.getInstance().getAllEngineers(new AsyncCallback<List<UIStaff>>() {
            @Override
            public void onFailure(Throwable caught) {
                Dialog.getInstance().createDialogBoxWithMessage("Error", caught.getMessage());
            }

            @Override
            public void onSuccess(List<UIStaff> result) {
                for (UIStaff uiStaff : result)
                    if (existingOrder.getEngineerId() == uiStaff.getStaffId()) {
                        engineerList.addItem(uiStaff.getFirstName() + " " + uiStaff.getLastName());
                        break;
                    }
            }
        });

        UserService.App.getInstance().getHistoryByOrderId(uiOrder.getOrderId(), new AsyncCallback<List<UIHistory>>() {
            @Override
            public void onFailure(Throwable throwable) {
                Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
            }

            @Override
            public void onSuccess(List<UIHistory> uiHistories) {
                ListDataProvider<UIHistory> dataProvider = new ListDataProvider<UIHistory>(uiHistories);
                dataProvider.addDataDisplay(orderHistoryCellTable.getOrderHistoryCellTable());
                center();
            }
        });

        UserService.App.getInstance().getServiceByOrderId(existingOrder.getOrderId(), new AsyncCallback<List<UIService>>() {
            @Override
            public void onFailure(Throwable throwable) {
                Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
            }

            @Override
            public void onSuccess(List<UIService> result) {
                servicesOnOrderToShow = new ArrayList<UIService>(result);
                ListDataProvider<UIService> dataProvider = new ListDataProvider<UIService>(servicesOnOrderToShow);
                dataProvider.addDataDisplay(serviceCellTable.getServiceCellTable());
                UserService.App.getInstance().getEquipmentByServicesList(servicesOnOrderToShow, new AsyncCallback<List<UIEquipment>>() {
                    @Override
                    public void onFailure(Throwable throwable) {
                        Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                    }

                    @Override
                    public void onSuccess(List<UIEquipment> uiEquipments) {
                        final List<UIEquipment> equipmentToShow = new ArrayList<UIEquipment>(uiEquipments);
                        UserService.App.getInstance().getEquipmentByOrderId(existingOrder.getOrderId(), new AsyncCallback<List<UIEquipment>>() {
                            @Override
                            public void onFailure(Throwable throwable) {
                                Dialog.getInstance().createDialogBoxWithMessage("Error", throwable.getMessage());
                            }

                            @Override
                            public void onSuccess(List<UIEquipment> uiEquipments) {
                                equipmentOnOrderToShow = new ArrayList<UIEquipment>(uiEquipments);
                                equipmentToShow.addAll(equipmentOnOrderToShow);
                                ListDataProvider<UIEquipment> dataProvider = new ListDataProvider<UIEquipment>(equipmentToShow);
                                dataProvider.addDataDisplay(equipmentCellTable.getEquipmentCellTable());
                                center();
                            }
                        });
                    }
                });
            }
        });
    }

    interface ClosedOrderViewUiBinder extends UiBinder<HTMLPanel, ClosedOrderView> {
    }
}